package com.netty.chat.controller;

import com.netty.chat.server.ChatHandler;
import com.netty.chat.service.ChatService;
import com.netty.chat.vo.CreateGroupRequest;
import com.netty.chat.vo.GroupChat;
import com.netty.chat.vo.UserInfo;
import com.netty.chat.vo.UserSocketChannel;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static com.netty.chat.server.ChatHandler.chatRecord;

@Controller
public class ChatController {
    @Autowired
    ChatService chatService;

    @RequestMapping("/createGroup")
    @ResponseBody
    public String createGroup(@RequestBody CreateGroupRequest request){
        System.out.println(request);
        GroupChat groupChat = new GroupChat();
        groupChat.setCreator(request.getUserInfo());
        int i = new Random().nextInt(4) + 1;
        groupChat.setIcon("/static/images/media_0"+i+".png");
        groupChat.setGroupName(request.getGroupName());
        groupChat.setGroupDesc(request.getGroupDesc());
        List<Integer> memberIds = request.getMemberIds();
        Set<UserInfo> members = chatService.getChannelByIds(memberIds);
        groupChat.setMembers(members);
        //随机生成的5位随机字符串作为群聊的唯一标识符
        String groupId = UUID.randomUUID().toString().substring(0,5);
        ChatHandler.groupChannel.put(groupId,groupChat);
        //初始化群聊聊天记录
        chatRecord.put(groupId,new ArrayList<>());
        return "success";
    }

    @RequestMapping("/disbandGroupChat")
    public String disbandGroupChat(@RequestParam("channelId")String channelId,@RequestParam("sendId")Integer sendId){
        Map<String, GroupChat> channel = ChatHandler.groupChannel;
        GroupChat groupChat = channel.get(channelId);
        if (groupChat.getCreator().getId().equals(sendId)){
            //确定解除群聊是由创建者发起的才通过
            channel.remove(channelId);
        }
        return "redirect:/toChat";
    }
}
